import 'package:permission_handler/permission_handler.dart';

/// 权限类型枚举（可扩展）
enum AppPermission {
  camera,
  microphone,
  storage,
  location,
  locationAlways,
  notification,
  bluetooth,
}

class PermissionService {
  // 将枚举映射为 Permission
  static Permission _mapPermission(AppPermission perm) {
    switch (perm) {
      case AppPermission.camera:
        return Permission.camera;
      case AppPermission.microphone:
        return Permission.microphone;
      case AppPermission.storage:
        return Permission.storage;
      case AppPermission.location:
        return Permission.location;
      case AppPermission.locationAlways:
        return Permission.locationAlways;
      case AppPermission.notification:
        return Permission.notification;
      case AppPermission.bluetooth:
        return Permission.bluetooth;
    }
  }

  /// 查询单个权限状态
  static Future<PermissionStatus> check(AppPermission perm) async {
    final permission = _mapPermission(perm);
    return permission.status;
  }

  /// 请求单个权限
  static Future<PermissionStatus> request(AppPermission perm) async {
    final permission = _mapPermission(perm);
    final status = await permission.request();
    return status;
  }

  /// 批量请求权限
  static Future<Map<AppPermission, PermissionStatus>> requestMultiple(
      List<AppPermission> perms) async {
    final permissions =
        perms.map((e) => _mapPermission(e)).toList(growable: false);
    final result = await permissions.request();
    final Map<AppPermission, PermissionStatus> mappedResult = {};
    for (var perm in perms) {
      mappedResult[perm] = result[_mapPermission(perm)]!;
    }
    return mappedResult;
  }

  /// 判断权限是否永久拒绝
  static Future<bool> isPermanentlyDenied(AppPermission perm) async {
    final status = await check(perm);
    return status.isPermanentlyDenied;
  }

  /// 打开系统设置页面
  static Future<void> openSettings() async {
    await openAppSettings();
  }

  /// 示例：统一处理权限，拒绝时弹窗跳转设置
  static Future<bool> ensurePermission(AppPermission perm) async {
    var status = await check(perm);
    if (status.isGranted) return true;

    status = await request(perm);
    if (status.isGranted) return true;

    if (status.isPermanentlyDenied) {
      // TODO: 可以弹出提示框告诉用户去设置打开权限
      await openSettings();
    }
    return false;
  }
}